﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using DotnetSpider.Http;
using Newtonsoft.Json.Linq;
 

namespace DotnetSpider.Agent
{
    public static class TokenHelper
	{

		public static void UpdateRequest(Request request)
		{
			return;
			if (!request.RequestUri.AbsolutePath.Contains("rest.q4w"))
			{
				return;
			}

			int retry_index = 0;
			int retry_max = 100;
			string cookie = string.Empty;
			string url = string.Empty;
			string urlStarts = "http://wenshu.court.gov.cn/website/parse/rest.q4w?HifJzoc9=";

			try
			{
				do
				{

					try
					{

						string tokenText = string.Empty;

						string queueId = string.Empty;


						for (int i = 0; i < 1000; i++)
						{
							queueId = RedisHelpers.ListRightPop<string>("LawyeeApi");

							if (RedisClient.Database.KeyExists(queueId))
							{
								tokenText = RedisHelpers.StringGet<string>(queueId);

								if (!string.IsNullOrEmpty(tokenText))
								{
									break;
								}
							}
						}
						 

						if (!string.IsNullOrEmpty(tokenText) && tokenText.StartsWith("{") && tokenText.EndsWith("}"))
						{
							JObject jobj = JObject.Parse(tokenText);

							if (jobj.Property("cookie") != null && jobj.Property("hifJzoc9") != null)
							{
								cookie = jobj["cookie"].ToString();
								url = urlStarts + jobj["hifJzoc9"].ToString();
							}

						}

						if (string.IsNullOrEmpty(cookie))
						{
							//Log.Logger.Warning("服务器获取Token失败，等待重新获取中......");
							Thread.Sleep(1000);
						}

					}
					catch (Exception ex)
					{

						//Log.Logger.Error(ex.ToString());
					} 

				} while (retry_index < retry_max && string.IsNullOrEmpty(cookie));

				Tuple<string, string> tokenResult = new Tuple<string, string>(cookie, url);

				request.RequestUri = new Uri(url);

				if (request.Headers.ContainsKey("Cookie"))
				{
					request.Headers["Cookie"] = cookie; 
				}
				else
				{ 
					request.Headers.Add("Cookie", cookie); 
				}

			}
			catch (Exception ex)
			{
				//Log.Logger.Error(ex.ToString());
			}



		}
	}
}
